package com.leochin.asynctaskdemo;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
	
	private Button mDownloadButton;
	private ProgressBar mPbar;
	private TextView mShowText;
	
	private int count;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		this.mDownloadButton = (Button)findViewById(R.id.main_download_button);
		this.mPbar = (ProgressBar)findViewById(R.id.main_progress_bar);
		this.mShowText = (TextView)findViewById(R.id.main_show_textview);
		
		this.mDownloadButton.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	
	/**
	 * 
	 * AsyncTask<Void, Integer, Void>
	 * 
	 * 指定的三个参数：
	 * 1. 必须是包装类型
	 * 2. 三个参数是为不同的方法准备的：Param,Progress,Result
	 * 
	 */
	public class DownloadTask extends AsyncTask<Void, Integer, Void>{

		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			
			Log.d("wenhao","onPreExecute..."+Thread.currentThread().getName());
		}
		
		/**
		 * 
		 * 在后台线程中运行
		 */
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			Log.d("wenhao","onInBackground..."+Thread.currentThread().getName());
			
			for(count = 1; count <= 100; count++){
				
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				this.publishProgress(count);
			}
			
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			Log.d("wenhao","onPostExecute..."+Thread.currentThread().getName());
			
			
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			Log.d("wenhao","onProgressUpdate...");
			
			int progress = values[0];
			mShowText.setText("已经完成 "+progress+"%");
			mPbar.setProgress(progress);
		}

	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int key = v.getId();
		
		switch (key) {
		case R.id.main_download_button:
			
			DownloadTask dt = new DownloadTask();
			dt.execute();
			
			break;

		default:
			break;
		}
	}


}
